package com.szgd.service.project;

import com.szgd.dao.ecdata.project.ProjectMapper;
import com.szgd.paging.Order;
import com.szgd.paging.PageBounds;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.util.Constant;
import com.szgd.util.StringUtil;
import com.szgd.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.*;

@Service
public class ProjectService extends SimulateBaseService {

    @Autowired
    ProjectMapper projectMapper;

    public void setAllProject(HttpSession httpSession) {
        List<Map<String,Object>> projectList = projectMapper.getProjectList(null);
        if (projectList == null || projectList.size() == 0)
            return;
        httpSession.setAttribute("projectList", projectList);
    }

    public List<Map<String, Object>> getProjectListNoPage(Map<String, Object> paramsMap) {
        List<Map<String,Object>> projectList = projectMapper.getProjectList(paramsMap);
        return projectList;
    }

    public List<Map<String, Object>> getProjectList(Map<String, Object> params) {
        String sortColumn = "ID"; //默认的排序列
        String sortType = "DESC";
        String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
        String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
        if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
            sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
            sortType = sSortDir_0;
        }
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        List<Map<String, Object>>  projectList = getSqlSession().selectList("com.szgd.dao.ecdata.project.ProjectMapper.getProjectList", params,pageBounds);
        return projectList;
    }

    public Map<String, Object> getProject(String id) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id",id);
        List<Map<String,Object>> projectList = projectMapper.getProjectList(paramsMap);
        if (projectList == null || projectList.size() == 0)
            return null;
        return projectList.get(0);
    }

    public void insertProject(Map<String, Object> paramsMap) {
        projectMapper.insertProject(paramsMap);
    }

    public void updateProject(Map<String, Object> paramsMap) {

        projectMapper.updateProject(paramsMap);
    }

    public Map<String, String> getFieldMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

        fieldMapping.put("number","项目编号");
        fieldMapping.put("name","项目名称");
        fieldMapping.put("inCharge","联系人");
        fieldMapping.put("partyA","甲方");
        fieldMapping.put("partyB","乙方");
        fieldMapping.put("beginTime","项目开始日期");
        fieldMapping.put("endTime","项目结束日期");
        fieldMapping.put("money","项目金额");
        fieldMapping.put("contractNumber","合同编号");
        fieldMapping.put("contractName","合同名称");
        fieldMapping.put("isKey","是否为重点项目");

        return fieldMapping;
    }

    public Map<String, Object> batchImportProjectInfo(List<Map<String, Object>> projectInfoList,String userId,String batchNo) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> successList = new ArrayList<>();   //记录导入成功的数据
        List<Map<String, Object>> updateList = new ArrayList<>();   //记录更新的数据
        List<Map<String, Object>> failedList = new ArrayList<>();   //记录导入失败的数据
        List<Map<String, Object>> ignoreList = new ArrayList<>();   //记录忽略的数据


        for (Map<String, Object> projectInfoMap : projectInfoList) {

            HashMap<String, Object> sourceDataMap = new HashMap<String, Object>(projectInfoMap);
            try {
                //判断项目编号是否存在
                if(projectInfoMap.get("number") != null && StringUtil.isNotBlank(String.valueOf(projectInfoMap.get("number")))) {

                }else{
                    sourceDataMap.put("ERROR_MSG","项目编号为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                //判断项目名称是否存在
                if(projectInfoMap.get("name") != null && StringUtil.isNotBlank(String.valueOf(projectInfoMap.get("name")))) {

                }else{
                    sourceDataMap.put("ERROR_MSG","项目名称为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                //验证日期是否准确
                if(projectInfoMap.get("beginTime") != null && StringUtil.isNotBlank(String.valueOf(projectInfoMap.get("beginTime")))) {
                    String beginTime = projectInfoMap.get("beginTime").toString();
                    boolean res = TimeUtil.isValidDate(beginTime);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","项目开始日期填写不正确");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                if(projectInfoMap.get("endTime") != null && StringUtil.isNotBlank(String.valueOf(projectInfoMap.get("endTime")))) {
                    String endTime = projectInfoMap.get("endTime").toString();
                    boolean res = TimeUtil.isValidDate(endTime);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","项目结束日期填写不正确");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                if(projectInfoMap.get("beginTime") != null && StringUtil.isNotBlank(String.valueOf(projectInfoMap.get("beginTime")))&&projectInfoMap.get("endTime") != null && StringUtil.isNotBlank(String.valueOf(projectInfoMap.get("endTime")))) {
                    String beginTime = projectInfoMap.get("beginTime").toString();
                    String endTime = projectInfoMap.get("endTime").toString();
                    if(endTime.compareTo(beginTime)<0){
                        sourceDataMap.put("ERROR_MSG","结束日期不能小于开始日期");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断金额
                if(projectInfoMap.get("money") != null && StringUtil.isNotBlank(String.valueOf(projectInfoMap.get("money")))) {
                    boolean res = isNumeric(projectInfoMap.get("money").toString());
                    if(res==false){
                        sourceDataMap.put("ERROR_MSG","金额必须填数字");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断是否为重点项目
                if(projectInfoMap.get("isKey") != null && StringUtil.isNotBlank(String.valueOf(projectInfoMap.get("isKey")))) {
                    String isKey = projectInfoMap.get("isKey").toString();
                    if (isKey.equalsIgnoreCase("是")){
                        projectInfoMap.put("isKey",1);
                    }
                    else if (isKey.equalsIgnoreCase("否")){
                        projectInfoMap.put("isKey",0);
                    }
                    else{
                        projectInfoMap.put("isKey",null);
                    }
                }

                projectInfoMap.put("creator",userId);

                Map<String, Object> paramMap = new HashMap<String, Object>();
                paramMap.put("number",projectInfoMap.get("number"));
                List<Map<String, Object>>  projectList =  this.getProjectListNoPage(paramMap);
                if (projectList != null && projectList.size() > 0)
                {
                    projectInfoMap.put("id",projectList.get(0).get("id"));
                    projectInfoMap.put("uploader",userId);
                    projectMapper.updateProject(projectInfoMap);
                    updateList.add(projectInfoMap);
                }
                else {
                    projectMapper.insertProject(projectInfoMap);
                    successList.add(projectInfoMap);
                }
            }catch (Exception e){
                String errorMsg = e.getMessage();
                if(errorMsg.indexOf("###",10) != -1){
                    errorMsg = errorMsg.substring(0,errorMsg.indexOf("###",10));
                }
                sourceDataMap.put("ERROR_MSG",errorMsg);
                //记录导入失败记录
                failedList.add(sourceDataMap);
            }
        }

        //组装本次导入的结果
        resultMap.put(Constant.IMPORT_HE_SUCCESS,successList);
        resultMap.put(Constant.IMPORT_HE_IGNORE,ignoreList);
        resultMap.put(Constant.IMPORT_HE_FAILED,failedList);
        resultMap.put(Constant.IMPORT_HE_UPDATED,updateList);
        return resultMap;
    }

    public void deleteProject(Map<String, Object> paramsMap) {
        projectMapper.deleteProject(paramsMap);
    }

    //判断是否为数字
    public static boolean isNumeric(String str){
        for (int i = str.length();--i>=0;){
            if (!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }
}
